import tkinter as tk
from socket import *
import time
import configparser
import threading

# 创建主窗口
window = tk.Tk()
window.title("FTC961 UDP Server")
window.resizable(False, False)
width = 300
height = 100
screenwidth = window.winfo_screenwidth()
screenheight = window.winfo_screenheight()
size_geo = f'{width}x{height}+{(screenwidth - width)//2}+{(screenheight - height)//2}'
window.geometry(size_geo)

# 全局变量（包括新增的 total_bytes）
udpSersock = None
server_running = False
total_bytes = 0  # 全局变量：记录总字节数
config = configparser.ConfigParser()

# 读取端口配置
try:
    config.read('configure.ini')
    port = int(config.get('Section1', 'Port'))
except Exception as e:
    print(f"配置文件读取错误: {e}")
    port = 8888  # 默认端口

def start_server():
    global udpSersock, server_running, total_bytes  # 声明使用全局变量
    if server_running:
        return
    
    # 启动服务器时重置总字节数为0
    total_bytes = 0
    allbytes.config(text='0')  # 同步更新标签显示
    
    start_button.config(state='disabled')
    stop_button.config(state='normal')
    
    # 创建UDP套接字并绑定
    host = ''
    buffsize = 65535
    Addr = (host, port)
    udpSersock = socket(AF_INET, SOCK_DGRAM)
    try:
        udpSersock.bind(Addr)
        print(f"UDP服务器启动成功，监听端口: {port}")
    except Exception as e:
        print(f"套接字绑定错误: {e}")
        udpSersock.close()
        udpSersock = None
        start_button.config(state='normal')
        return

    server_running = True
    # 启动线程处理网络通信
    thread = threading.Thread(target=server_thread, daemon=True)
    thread.start()

def server_thread():
    global server_running, total_bytes  # 声明使用全局变量
    time1 = time.strftime('%Y%m%d%H%M%S')
    
    with open(f'data{time1}.txt', 'w', buffering=1, encoding='utf-8') as f:
        while server_running:
            try:
                udpSersock.settimeout(1)  # 超时避免阻塞
                data, addr = udpSersock.recvfrom(65535)
                current_time = time.strftime('%Y-%m-%d %H:%M:%S')
                hex_str = data.hex()
                
                # 累加总字节数（当前数据包的字节数 = len(data)）
                total_bytes += len(data)
                
                # 生成ACK并发送
                bytes_data = bytes.fromhex(hex_str)
                byte3 = bytes_data[2]
                byte4 = bytes_data[3]
                byte5 = bytes_data[5]
                byte6 = bytes_data[-1]
                ack_bytes = bytes([0x00, 0x05, byte3, byte4, 0x01, byte5, byte6])
                udpSersock.sendto(ack_bytes, addr)
                
                # 写入文件并更新GUI显示总字节数
                f.write(f"{current_time} {hex_str}\n")
                # 修复：使用 total_bytes 而非未定义的 data_length
                window.after(0, lambda: allbytes.config(text=str(total_bytes)))
                
            except timeout:
                continue  # 超时不处理
            except Exception as e:
                if server_running:
                    print(f"接收错误: {e}")
                break

    # 线程结束后清理
    window.after(0, stop_server)

def stop_server():
    global server_running, udpSersock
    server_running = False
    if udpSersock:
        try:
            udpSersock.close()
            print("服务器已关闭")
        except:
            pass
        udpSersock = None
    start_button.config(state='normal')
    stop_button.config(state='disabled')

# GUI组件
start_button = tk.Button(window, text='打开服务器', pady=1, padx=1, command=start_server, width=12, height=1)
start_button.place(relx=0.1, rely=0.1)

stop_button = tk.Button(window, text='关闭服务器', pady=1, padx=1, command=stop_server, width=12, height=1)
stop_button.place(relx=0.6, rely=0.1)
stop_button.config(state='disabled')  # 初始禁用

allbytes_label = tk.Label(window, text='总字节数:', justify='center', width=8, height=1)
allbytes_label.place(relx=0.2, rely=0.6)

allbytes = tk.Label(window, text='0', justify='center', width=15, height=1)
allbytes.place(relx=0.4, rely=0.6)

window.mainloop()
